//
//  RBRegularWebView.m
//  zhongzhenglu
//
//  Created by mac on 2022/10/17.
//

#import "RBRegularWebView.h"
#import <WebKit/WebKit.h>
#import <Masonry.h>
#import "RBThemeConfig.h"
#import "RBURLConfig.h"
#import <UIView+YYAdd.h>
#import "UIViewController+RBAdd.h"

@interface RBRegularWebView()<WKUIDelegate, WKNavigationDelegate>

@property (strong, nonatomic) WKWebView *webview;
@property(nonatomic, strong) UIActivityIndicatorView *indicatorView;

@end

@implementation RBRegularWebView

#pragma mark - System

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.clipsToBounds = YES;
    }
    return self;
}

- (void)dealloc
{
    [_webview.scrollView removeObserver:self forKeyPath:@"contentSize"];
    [_webview removeObserver:self forKeyPath:@"estimatedProgress"];
}

#pragma mark - Public

- (void)setHtmlString:(NSString *)htmlString
{
    self.indicatorView.hidden = NO;
    [self.indicatorView startAnimating];
    
    if (![htmlString containsString:@"<p>"])
    {
        htmlString = [NSString stringWithFormat:@"<p>%@<\/p>", htmlString];
    }
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"<img" withString:@"<img onclick='show(this.src)' "];
    
    NSString *newHtmlString = [NSString stringWithFormat:@"<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'><meta name='apple-mobile-web-app-capable' content='yes'><meta name='apple-mobile-web-app-status-bar-style' content='black'><meta name='format-detection' content='telephone=no'><script>function show(s){document.location = '%@'+s;}</script><style type='text/css'>img{width:100%%}p{%@}</style>%@", @"", self.preferStyle,htmlString];

//    NSString *newHtmlString = [NSString stringWithFormat:@"<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'><meta name='apple-mobile-web-app-capable' content='yes'><meta name='apple-mobile-web-app-status-bar-style' content='black'><meta name='format-detection' content='telephone=no'><style type='text/css'>img{width:100%%}p{font-size:13px;line-height:28px;color:#333333}</style>%@", htmlString];
    
    [self.webview loadHTMLString:newHtmlString baseURL:[NSURL URLWithString:[[RBURLConfig shareInstance] commonServicePicUrl]]];
    
    [self bringSubviewToFront:self.indicatorView];
}

- (void)setUrl:(NSString *)url
{
    [self.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
    [self bringSubviewToFront:self.indicatorView];
}

#pragma mark - Event

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"contentSize"])
    {
        CGFloat currentHeight = MAX(self.webview.scrollView.contentSize.height, 30);
        [self.webview mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(MAX(self.webview.scrollView.contentSize.height, 10));
        }];
        [self mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(currentHeight);
        }];
    }
    else if([keyPath isEqualToString:@"estimatedProgress"])
    {
        if (self.webview.estimatedProgress > 0.1)
        {
            [self.indicatorView stopAnimating];
            self.indicatorView.hidden = YES;
        }
    }
}

#pragma mark - Delegate

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation

{
    
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSString *path = navigationAction.request.URL.absoluteString;
    path = [path stringByReplacingOccurrencesOfString:[[RBURLConfig shareInstance] commonServicePicUrl] withString:@""];
//    if ([path hasPrefix:kJumpPre])
//    {
//        path = [path stringByReplacingOccurrencesOfString:kJumpPre withString:@""];
//        path = [RBURLConfig adjustImageUrl:path];
//        [self.viewController showWithImages:@[path] index:0 imageViews:nil];
//        decisionHandler(WKNavigationActionPolicyCancel);
//    }
//    else
//    {
        decisionHandler(WKNavigationActionPolicyAllow);
//    }
}
#pragma mark - Setter

#pragma mark - Getter

- (WKWebView *)webview
{
    if (!_webview)
    {
        self.webview = ({
            WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
            WKWebView *view = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
            view.UIDelegate = self;
            view.navigationDelegate = self;
            
            view.backgroundColor = [UIColor clearColor];
            view.opaque = NO;
            view.allowsBackForwardNavigationGestures = YES;
            view.scrollView.scrollEnabled = NO;
            [view.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:NULL];
            [view addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
            
            [self addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(0);
                make.left.right.mas_equalTo(0);
                make.height.mas_equalTo(10);
            }];
            view;
        });
    }
    return _webview;
}

- (UIActivityIndicatorView *)indicatorView
{
    if (!_indicatorView)
    {
        self.indicatorView = ({
            UIActivityIndicatorView *view = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            [self addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.height.mas_equalTo(15);
                make.center.mas_equalTo(0);
            }];
            
            view;
        });
    }
    return _indicatorView;
}

@end

